package com.school.information.core.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

@Slf4j
@Component
public class CustomPasswordService implements PasswordEncoder {
    public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

    public static final int SALT_BYTE_SIZE = 16;         //盐的长度
    public static final int HASH_BIT_SIZE = 48;         //生成密文的长度
    public static final int PBKDF2_ITERATIONS = 1024;        //迭代次数

    /**
     * @auther: yuchuanchuan
     * @describe: 生成密文
     * @param: [password(明文密码), salt(盐值)]
     * @return: java.lang.String
     * @date: 2018/11/2
     */
    public String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        // 将16进制的字符串 salt 转换为二进制 byte数组
        byte[] bytes = DatatypeConverter.parseHexBinary(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, PBKDF2_ITERATIONS, HASH_BIT_SIZE * 4);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
        byte[] resultBytes = secretKeyFactory.generateSecret(spec).getEncoded();
        // 将二进制 byte 数组转换为 十六进制的字符串
        return DatatypeConverter.printHexBinary(resultBytes);
    }

    static boolean checkPassword(String password) {
        return StringUtils.isBlank(password) || password.length() < SALT_BYTE_SIZE + HASH_BIT_SIZE;
    }


    /**
     * @auther: yuchuanchuan
     * @describe: 通过加密的强随机数生成盐(最后转换为16进制)
     * @param: []
     * @return: java.lang.String
     * @date: 2018/11/2
     */
    public String newSalt() throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[SALT_BYTE_SIZE / 2];
        random.nextBytes(salt);
        // 将 二进制byte数组转换为16进制字符串
        return DatatypeConverter.printHexBinary(salt);
    }

    @Override
    public String encode(CharSequence rawPassword) {
        try {
            String salt = newSalt();
            return salt + getEncryptedPassword((String) rawPassword, salt);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param rawPassword     原始密码
     * @param encodedPassword 加密密码
     * @return true表示密码正确 flase 密码错误
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (StringUtils.isBlank(rawPassword) || checkPassword(encodedPassword)) {
            return false;
        }
        try {
            String salt = encodedPassword.substring(0, SALT_BYTE_SIZE);
            String cipherText = encodedPassword.substring(SALT_BYTE_SIZE);
            return authenticate((String) rawPassword, salt, cipherText);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @auther: yuchuanchuan
     * @desc: 对输入的密码进行验证
     * @param: [attemptedPassword(待验证密码), encryptedPassword(密文), salt(盐值)]
     * @return: boolean
     * @date: 2018/11/2
     */
    public boolean authenticate(String attemptedPassword, String salt, String encryptedPassword)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 用相同的盐值对用户输入的密码进行加密
        String result = getEncryptedPassword(attemptedPassword, salt);
        // 把加密后的密文和原密文进行比较，相同则验证成功，否则失败
        return result.equals(encryptedPassword);
    }

    /**
     * 生成加密后的密码串
     *
     * @param password
     * @return
     */
    public String generatePassword(String password) {
        try {
            String salt = newSalt();
            return salt + getEncryptedPassword(password, salt);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    //    public static void main(String[] args) throws Exception{
//
//        String salt = newSalt();
//        System.out.println("salt:" + salt);
//        String password = "123456";
//        String cipherText = getEncryptedPassword(password, salt);
//        System.out.println("密码密文: " + cipherText);
//        System.out.println("密码密文校验:" + authenticate(password, salt, cipherText));
//        String encryptedPassword = generatePassword(password);
//        System.out.println("salt和密码密文组成: " + encryptedPassword);  // salt + 密码密文
//        System.out.println("salt和密码密文校验:" + verifyPassword(password, encryptedPassword));
//
//    }
}
